#include <iostream>
#include <cerrno>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>
#include "Comm.h"
#include <netinet/in.h>
#include <arpa/inet.h>

void Usage(std::string proc)
{
    std::cout << "Usage: \n\t" << proc << " local_ip local_port\n"
              << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3) // 参数数量
    {
        Usage(argv[0]);
        return Usage_Err;
    }

    std::string serverip = argv[1];           // ip地址
    uint16_t serverport = std::stoi(argv[2]); // 端口号

    // 创建套接字
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        std::cerr << "Socket Error! " << strerror(errno) << std::endl;
        return 1;
    }

    std::cout << "Create socket success!" << std::endl;
    // client 不需要进行bind,客户端很多，需要随机绑定
    //  client 需要bind,但是不需要显示bind,

    struct sockaddr_in server;
    //socklen_t len = sizeof server;
    bzero(&server, sizeof server);

    server.sin_family =AF_INET;
    server.sin_port =htons(serverport);
    //server.sin_addr.s_addr = inet_addr(serverip.c_str()) ;
    server.sin_addr.s_addr = inet_addr(serverip.c_str()) ;


    while (1)
    {
        std::string in_buffer;
        std::cout << "Please Enter: " << std::endl;
        std::getline(std::cin, in_buffer);

        size_t n = sendto(sock,in_buffer.c_str(),in_buffer.size(),0,(struct sockaddr*)&server,sizeof server);
        if(n>0)
        {
            char buffer[1024];
            struct sockaddr_in temp;
            socklen_t len = sizeof temp;

            //发送完消息后，在recvfrom中堵塞等待服务端的消息
            ssize_t m = recvfrom(sock,buffer,sizeof buffer - 1,0,(struct sockaddr*)&temp,&len);

            if(m>0)
            {
                buffer[m]=0;
                std::cout<<"Server # say: "<<buffer<<std::endl;
            }
            else
            break;
        }
        else
        {
            break;
        }
    }

    close(sock);
}